package com.whisperly.echotalk.starryb.schemas;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.os.Build;
import android.os.Bundle;
import android.os.LocaleList;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;

import com.appsflyer.AFInAppEventType;
import com.appsflyer.AppsFlyerLib;
import com.appsflyer.attribution.AppsFlyerRequestListener;
import com.google.android.gms.auth.api.signin.GoogleSignIn;
import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
import com.google.android.gms.auth.api.signin.GoogleSignInClient;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GoogleApiAvailability;
import com.google.android.gms.common.api.ApiException;
import com.google.android.gms.tasks.Task;
import com.google.android.material.button.MaterialButton;
import com.whisperly.echotalk.account.FindPassword;
import com.whisperly.echotalk.bllmodel.BaseResponse;
import com.whisperly.echotalk.bllmodel.LoginDto;
import com.whisperly.echotalk.bllmodel.LoginResponse;
import com.whisperly.echotalk.bllmodel.ResultBody;
import com.whisperly.echotalk.bllmodel.SignUp;
import com.whisperly.echotalk.bllmodel.UserWithChat;
import com.whisperly.echotalk.starryb.R;
import com.whisperly.echotalk.starryb.netWorkUtils.BlinkCallback;
import com.whisperly.echotalk.starryb.netWorkUtils.NetworkUtils;
import com.whisperly.echotalk.starryb.utils.GlobalData;

import java.util.HashMap;
import java.util.Locale;
import java.util.Map;


public class Login extends AppCompatActivity {

    private EditText user_name;
    private EditText psw;
    private Button login;
    private TextView register;
    private TextView find_psw;
    private MaterialButton googleSignInButton;
    private GoogleSignInClient mGoogleSignInClient;
    private static final int RC_SIGN_IN = 9001;
    private static final int RC_PLAY_SERVICES = 9002;
    private View loadingView;
    private final static String TAG = "Login";
    private final int requestPermissionCode = this.hashCode();
    private CheckBox rememberMe;
    private SharedPreferences loginPrefs;
    private static final String PREF_NAME = "LoginPrefs";
    private static final String KEY_REMEMBER = "remember";
    private static final String KEY_USERNAME = "username";
    private static final String KEY_PASSWORD = "password";
    private static final String KEY_LOGIN_TYPE = "login_type";
    @Override
    protected void attachBaseContext(Context newBase) {
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(newBase);
        String languageCode = prefs.getString("language", "en");
        super.attachBaseContext(updateResources(newBase, languageCode));
    }

    public Context updateResources(Context context, String languageCode) {
        Locale locale = new Locale(languageCode);
        Locale.setDefault(locale);

        Resources res = context.getResources();
        Configuration config = new Configuration(res.getConfiguration());
        config.setLocale(locale);
        LocaleList localeList = new LocaleList(locale);
        LocaleList.setDefault(localeList);
        config.setLocales(localeList);
        context = context.createConfigurationContext(config);
        return context;
    }

    private void signIn() {
        showLoading();
        Intent signInIntent = mGoogleSignInClient.getSignInIntent();
        startActivityForResult(signInIntent, RC_SIGN_IN);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == RC_SIGN_IN) {
            Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data);
            try {
                GoogleSignInAccount account = task.getResult(ApiException.class);
                handleGoogleSignInResult(account);
            } catch (ApiException e) {
                Log.w(TAG, "Google sign in failed", e);
                hideLoading();
                showLoginDialog(getString(R.string.google_sign_in_failed), false);
            }
        }
    }

    private void handleGoogleSignInResult(GoogleSignInAccount account) {
        String email = account.getEmail();
        String name = account.getDisplayName();

        // 添加加载动画
        showLoading();

        // 这里你可以使用Google账号信息进行登录或注册
        LoginDto loginDto = new LoginDto();
        loginDto.setUserName(name);
        loginDto.setEmail(email);
        loginDto.setType("Google");
        loginDto.setPassword(""); // 可能需要一个特殊的处理方式来处理Google登录

        NetworkUtils.postLogin(loginDto, new BlinkCallback() {
            @Override
            public void onSuccess(ResultBody<?> response) {
                // 确保在主线程中处理 UI 操作
                runOnUiThread(() -> {
                    hideLoading();
                    try {
                        LoginResponse data = (LoginResponse)response.getData();
                        UserWithChat user = data.getUserWithChat();
                        if (data.getSuccess()){
                            @SuppressLint("DefaultLocale") String loginId = "Blink " + user.getUid();
                            user.setLoginId(loginId);
                            GlobalData.setUsername(name);
                            GlobalData.setUser(user.getObjectId(), user);

                            NetworkUtils.getByUserId(user.getObjectId(), new BlinkCallback() {
                                @Override
                                public void onSuccess(ResultBody<?> response) {
                                    runOnUiThread(() -> {
                                        try {
                                            if (response.getCode() == 200){
                                                BaseResponse<?> data1 = (BaseResponse<?>) response.getData();
                                                SignUp data2 = (SignUp) data1.getData();
                                                GlobalData.setSignup(data2);

                                                if (!isFinishing() && !isDestroyed()) {
                                                    // 显示Google账号登录成功和密码提示
                                                    showGoogleLoginSuccessDialog(email);
                                                    logLoginEvent(name);
                                                }
                                            } else {
                                                if (!isFinishing() && !isDestroyed()) {
                                                    showGoogleLoginSuccessDialog(email);
                                                }
                                            }
                                        } catch (Exception e) {
                                            Log.e(TAG, "Error processing success response", e);
                                            if (!isFinishing() && !isDestroyed()) {
                                                showLoginDialog(getString(R.string.Network_error), false);
                                            }
                                        }
                                    });
                                }

                                @Override
                                public void onFailure(Throwable throwable) {
                                    runOnUiThread(() -> {
                                        if (!isFinishing() && !isDestroyed()) {
                                            showLoginDialog(getString(R.string.Network_error), false);
                                        }
                                    });
                                }
                            });
                        } else {
                            if (!isFinishing() && !isDestroyed()) {
                                showLoginDialog(getString(R.string.Login_failed), false);
                            }
                        }
                    } catch (Exception e) {
                        Log.e(TAG, "Error processing login response", e);
                        if (!isFinishing() && !isDestroyed()) {
                            showLoginDialog(getString(R.string.Network_error), false);
                        }
                    }
                });
            }

            @Override
            public void onFailure(Throwable throwable) {
                runOnUiThread(() -> {
                    hideLoading();
                    if (!isFinishing() && !isDestroyed()) {
                        Log.e(TAG, "Google sign in API call failed", throwable);
                        showLoginDialog(getString(R.string.Network_error), false);
                    }
                });
            }
        });
        // 在登录成功后，如果勾选了记住我，保存Google账号信息
        if (rememberMe.isChecked()) {
            saveLoginCredentials(account.getEmail(), "", "google");
        }
    }

    private void saveLoginCredentials(String username, String password, String loginType) {
        SharedPreferences.Editor editor = loginPrefs.edit();
        editor.putBoolean(KEY_REMEMBER, true);
        editor.putString(KEY_USERNAME, username);
        editor.putString(KEY_PASSWORD, password);
        editor.putString(KEY_LOGIN_TYPE, loginType);
        editor.apply();
    }

    // 添加新方法显示Google登录成功和密码提示对话框
    private void showGoogleLoginSuccessDialog(String email) {
        if (isFinishing() || isDestroyed()) {
            return;
        }

        runOnUiThread(() -> {
            try {
                AlertDialog.Builder builder = new AlertDialog.Builder(this);
                builder.setTitle(R.string.Login_successful);

                // 创建包含登录成功和密码提示的完整消息
                String message = getString(R.string.Login_successful) + "\n\n" +
                        getString(R.string.google_login_password_notice, email);

                builder.setMessage(message);
                builder.setPositiveButton(R.string.OK, (dialog, which) -> {
                    dialog.dismiss();
                    if (!isFinishing() && !isDestroyed()) {
                        try {
                            Intent intent = new Intent(this, AI.class);
                            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
                            startActivity(intent);
                            finish();
                        } catch (Exception e) {
                            Log.e(TAG, "Error starting AI activity", e);
                        }
                    }
                });

                AlertDialog dialog = builder.create();
                dialog.setCancelable(false);

                if (!isFinishing() && !isDestroyed()) {
                    dialog.show();
                }
            } catch (Exception e) {
                Log.e(TAG, "Error showing Google login success dialog", e);
            }
        });
    }

    // 添加新方法来处理登录事件记录
    private void logLoginEvent(String name) {
        try {
            Map<String, Object> eventValues = new HashMap<>();
            eventValues.put(AFInAppEventType.LOGIN, name);
            AppsFlyerLib.getInstance().logEvent(getApplicationContext(),
                    AFInAppEventType.LOGIN, eventValues, new AppsFlyerRequestListener() {
                        @Override
                        public void onSuccess() {
                            Log.d(TAG, "Event sent successfully");
                        }
                        @Override
                        public void onError(int i, @NonNull String s) {
                            Log.d(TAG, "Event failed to be sent:\n" +
                                    "Error code: " + i + "\n"
                                    + "Error description: " + s);
                        }
                    });
        } catch (Exception e) {
            Log.e(TAG, "Error logging event", e);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 确保清理 loadingView
        if (loadingView != null && loadingView.getParent() != null) {
            ((ViewGroup) loadingView.getParent()).removeView(loadingView);
        }
        loadingView = null;
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login);

        loadingView = getLayoutInflater().inflate(R.layout.layout_loading, null);
        // 初始化 SharedPreferences
        loginPrefs = getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);

        user_name = findViewById(R.id.user_name);
        psw = findViewById(R.id.psw);
        rememberMe = findViewById(R.id.remember_me);

        user_name = findViewById(R.id.user_name);
        psw = findViewById(R.id.psw);
        login = findViewById(R.id.login);
        register = findViewById(R.id.register);
        find_psw = findViewById(R.id.find_psw);

        int available = GoogleApiAvailability.getInstance().isGooglePlayServicesAvailable(this);
        if (available != ConnectionResult.SUCCESS) {
            Dialog dialog = GoogleApiAvailability.getInstance().getErrorDialog(this, available, RC_PLAY_SERVICES);
            assert dialog != null;
            dialog.show();
        }

        // 初始化Google登录
        GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
                .requestEmail()
                .requestProfile()
                .build();
        mGoogleSignInClient = GoogleSignIn.getClient(this, gso);

        // 添加Google登录按钮
        googleSignInButton = findViewById(R.id.google_sign_in_button);
        googleSignInButton.setOnClickListener(v -> signIn());

        login.setOnClickListener(v -> {
            handleLogin();
        });

        register.setOnClickListener(v -> {
            Intent intent = new Intent(this, Register.class);
            startActivity(intent);
//            overridePendingTransition(R.anim.slide_up, R.anim.slide_down);
            finish();
        });

        find_psw.setOnClickListener(v -> {
            Intent intent = new Intent(this, FindPassword.class);
            startActivity(intent);
        });

        askNotificationPermission();
    }

    private void clearLoginCredentials() {
        SharedPreferences.Editor editor = loginPrefs.edit();
        editor.clear();
        editor.apply();
    }

    private void handleLogin() {
        showLoading();
        String name = user_name.getText().toString().trim();
        String password = psw.getText().toString().trim();

        if (name.isEmpty() || password.isEmpty()) {
            showLoginDialog(getString(R.string.The_account_number_or_password_cannot_be_empty), false);
            hideLoading();
            return;
        }

        LoginDto loginDto = new LoginDto();
        loginDto.setUserName(name);
        loginDto.setPassword(password);

        NetworkUtils.postLogin(loginDto, new BlinkCallback() {
            @Override
            public void onSuccess(ResultBody<?> response) {
                runOnUiThread(() -> {
                    hideLoading();
                    LoginResponse data = (LoginResponse)response.getData();
                    Log.e("data",data.toString());
                    if (data.getSuccess()) {
                        // 如果勾选了记住我，保存登录信息
                        if (rememberMe.isChecked()) {
                            saveLoginCredentials(name, password, "normal");
                        } else {
                            clearLoginCredentials();
                        }
                        UserWithChat user = data.getUserWithChat();
                        // 处理登录成功
                        handleLoginSuccess(user,name);
                    } else {
                        showLoginDialog(getString(R.string.The_account_number_or_password_is_incorrect), false);
                    }
                });
            }

            @Override
            public void onFailure(Throwable throwable) {
                Log.e("Login", "onFailure: " + throwable.toString());
                Toast.makeText(Login.this, R.string.Network_error, Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void handleLoginSuccess(UserWithChat user,String name) {
        @SuppressLint("DefaultLocale") String loginId = "Blink " + user.getUid();
        user.setLoginId(loginId);
        GlobalData.setUsername(name);
        GlobalData.setUser(user.getObjectId(), user);
        NetworkUtils.getByUserId(user.getObjectId(), new BlinkCallback() {
            @Override
            public void onSuccess(ResultBody<?> response) {
                if (response.getCode() == 200){
                    BaseResponse<?> data1 = (BaseResponse<?>) response.getData();
                    SignUp data2 = (SignUp) data1.getData();
                    GlobalData.setSignup(data2);
                    showLoginDialog(getString(R.string.Login_successful), true);
                    Map<String, Object> eventValues = new HashMap<String, Object>();
                    eventValues.put(AFInAppEventType.LOGIN, name);
                    AppsFlyerLib.getInstance().logEvent(getApplicationContext(),
                            AFInAppEventType.LOGIN, eventValues,new AppsFlyerRequestListener() {
                                @Override
                                public void onSuccess() {
                                    Log.d(TAG, "Event sent successfully");
                                }
                                @Override
                                public void onError(int i, @NonNull String s) {
                                    Log.d(TAG, "Event failed to be sent:\n" +
                                            "Error code: " + i + "\n"
                                            + "Error description: " + s);
                                }
                            });
                    return;
                }
                showLoginDialog(getString(R.string.Network_error), false);
            }

            @Override
            public void onFailure(Throwable throwable) {
                showLoginDialog(getString(R.string.Network_error), false);
            }
        });
    }

    // Declare the launcher at the top of your Activity/Fragment:
    private final ActivityResultLauncher<String> requestPermissionLauncher =
            registerForActivityResult(new ActivityResultContracts.RequestPermission(), isGranted -> {
                if (isGranted) {
                    // FCM SDK (and your app) can post notifications.

                } else {
                    // TODO: Inform user that that your app will not show notifications.
                }
            });

    private void askNotificationPermission() {
        // This is only necessary for API level >= 33 (TIRAMISU)
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.POST_NOTIFICATIONS) ==
                    PackageManager.PERMISSION_GRANTED) {
                // FCM SDK (and your app) can post notifications.
            } else if (shouldShowRequestPermissionRationale(Manifest.permission.POST_NOTIFICATIONS)) {
                // TODO: display an educational UI explaining to the user the features that will be enabled
                //       by them granting the POST_NOTIFICATION permission. This UI should provide the user
                //       "OK" and "No thanks" buttons. If the user selects "OK," directly request the permission.
                //       If the user selects "No thanks," allow the user to continue without notifications.
            } else {
                // Directly ask for the permission
                requestPermissionLauncher.launch(Manifest.permission.POST_NOTIFICATIONS);
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == requestPermissionCode) {
            // 处理回调结果
        }
    }

    private void showLoading() {
        // Ensure loadingView doesn't have a parent before adding it
        if (loadingView.getParent() == null) {
            ((ViewGroup) findViewById(android.R.id.content)).addView(loadingView);
            Log.d("LoginActivity", "Loading view added");
        }
    }

    private void hideLoading() {
        ((ViewGroup) findViewById(android.R.id.content)).removeView(loadingView);
    }

    private void showLoginDialog(String message, boolean flag) {
        if (isFinishing() || isDestroyed()) {
            return;
        }

        runOnUiThread(() -> {
            try {
                AlertDialog.Builder builder = new AlertDialog.Builder(this);
                builder.setTitle(R.string.Prompt);
                builder.setMessage(message);
                builder.setPositiveButton(R.string.OK, (dialog, which) -> {
                    dialog.dismiss();
                    if (flag && !isFinishing() && !isDestroyed()) {
                        try {
                            Intent intent = new Intent(this, AI.class);
                            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
                            startActivity(intent);
                            finish();
                        } catch (Exception e) {
                            Log.e(TAG, "Error starting AI activity", e);
                        }
                    }
                });
                AlertDialog dialog = builder.create();
                dialog.setCancelable(false);
                if (!isFinishing() && !isDestroyed()) {
                    dialog.show();
                }
            } catch (Exception e) {
                Log.e(TAG, "Error showing dialog", e);
            }
        });
    }
}
